package com.feeyo.monitor.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feeyo.monitor.domain.FenceId;
import com.feeyo.monitor.domain.FenceSend;
import com.feeyo.monitor.enumeration.HttpContentType;
import com.feeyo.monitor.mapper.FenceSendMapper;
import com.feeyo.monitor.service.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.feeyo.monitor.domain.LimitArea;
import com.feeyo.monitor.utils.GloabalConstant;
import com.feeyo.monitor.utils.ResultData;

/**
 * 限制区类rest接口
 * @Author <a href="mailto:bliulei@variflight.com">liulei</a>
 * @Description Created by liulei on 2017/5/18 下午5:42.
 */
@RestController
@RequestMapping("/monitor") 
public class LimitAreaController {

    Logger logger = LoggerFactory.getLogger(LimitAreaController.class);

	@Autowired
	UserVehiclePermissionService userVehiclePermissionService;
	@Autowired
	LimitAreaService limitAreaService;
	@Autowired
    VehicleService vehicleService;
	@Autowired
    FenceIdService fenceIdService;
	@Autowired
    HttpService httpService;
	@Autowired
    FenceSendMapper fenceSendMapper;
	
	/**
	 * @Description 限制区列表
	 * @params
	 * @return
	 */
	@RequestMapping(value="/limitAreas", method=RequestMethod.GET) 
	public ResultData<List<LimitArea>> getLimitAreas(@RequestParam(value="userId",required=true) String userId){
		ResultData<List<LimitArea>> rd = new ResultData<List<LimitArea>>();
		Map perm = userVehiclePermissionService.selectByUserId(userId);
		String airport = (String)perm.get("airport");
		if (airport != null){
			String[] arr = airport.split(",");
			airport = arr[0]; 
		}
		List<LimitArea> result = null;
		try{
			result = limitAreaService.selectByAirport(airport);
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			return rd;
		}

		rd.setCode(GloabalConstant.SUCCESS);
		rd.setData(result);
		return rd;
	}

	/**
	 * @Description 限制区详细信息
	 * @params
	 * @return
	 */
	@RequestMapping(value="/limitAreas/{areaId}", method=RequestMethod.GET) 
	public ResultData<LimitArea> getLimitArea(@PathVariable("areaId")String areaId){
		ResultData<LimitArea> rd = new ResultData<LimitArea>();
		LimitArea result = null;
		try{
			result = limitAreaService.selectByPrimaryKey(areaId);
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			return rd;
		}

		rd.setCode(GloabalConstant.SUCCESS);
		rd.setData(result);
		return rd;
	}

	/**
	 * @Description 新建/修改 限制区
	 * @params
	 * @return
	 */
	@RequestMapping(value="/limitArea", method=RequestMethod.POST) 
	public ResultData<Object> saveLimitArea(
            @RequestParam(value="id",required=false)String id,
	        @RequestParam(value="name",required=true)String name,
			@RequestParam(value="area",required=true)String area,
			@RequestParam(value="speed",required=true)double speed,
			@RequestParam(value="airport",required=true)String airport,
            @RequestParam(value="visible",required=true)Boolean visible,
            @RequestParam(value="depts",required=true)String depts,
            @RequestParam(value="types",required=true)String types,
            @RequestParam(value="areaType",required=true)Integer areaType){
		ResultData<Object> rd = new ResultData<Object>();
		//11459597.3948924,2888806.36771488;11459480.3506929,2888488.67631607;11459525.7351784,2888894.74802884;11459597.3948924,2888806.36771488
		//POLYGON((102.927574 25.102129, 102.93214 25.100378,102.935029 25.104862,102.929686 25.106812,102.927574 25.102129))
		String [] areaArr = area.split(";");
		StringBuilder sb = new StringBuilder();
		sb.append("POLYGON((");
		for(String lonlat : areaArr){
			sb.append(lonlat.replace(",", " ") + ",");
		}
		sb.setLength(sb.length()-1);
		sb.append("))");
		LimitArea limitArea = new LimitArea();
		limitArea.setId(id);
		limitArea.setName(name);
		limitArea.setArea(sb.toString());
		limitArea.setLimitSpeed(speed);
		limitArea.setPosowner(airport.toUpperCase());
		limitArea.setVisible(visible);
		limitArea.setDepts(depts);
		limitArea.setTypes(types);
		limitArea.setAreaType(areaType);
//        FenceId fenceId = fenceIdService.selectUsableId();
//        limitArea.setFence(fenceId.getFid());
		try{
            if (id == null)
			    limitAreaService.insert(limitArea);
            else
                limitAreaService.updateByPrimaryKeySelective(limitArea);
            //下发围栏指令
//            fenceSend(area,depts,types);
//            fenceIdService.updateTrueStatus(fenceId.getFid());//将这个fenceId变为占用状态
		}catch(Exception e){
			rd.setCode(-1);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}

		//取可用的围栏id，获取相关车辆编号列表，http下发指令
//        FenceId fenceId = fenceIdService.selectUsableId();
//        Map<Object, Object> perm = userVehiclePermissionService.selectByUserId(userId);
//		List<Map> vidList = vehicleService.selectIdByUser(perm);
//        int npts = area.split(",").length/2;
//        for(Map item:vidList){
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("devid",item.get("devid"));
//            JSONObject jsonFence = new JSONObject();
//            jsonFence.put("id",fenceId.getFid());
//            jsonFence.put("npts",npts);
//            jsonFence.put("pts",area);
//            jsonFence.put("alm",3);
//            jsonFence.put("speed",100);
//            jsonObject.put("fence",jsonFence);
//            httpService.post("http://114.112.63.147:8443/devctl/api/v1.0/fence", HttpContentType.JSON,jsonObject.toJSONString());
//        }

		rd.setCode(GloabalConstant.SUCCESS);
		rd.setData(limitArea);
		return rd;
	}

	/**
	 * @Description 删除限制区
	 * @params
	 * @return
	 */
	@RequestMapping(value="/limitArea/delete/{areaId}", method=RequestMethod.GET)
    //@Transactional
	public ResultData<Object> delete(@PathVariable("areaId")String areaId){
		ResultData<Object> rd = new ResultData<Object>();
		try{
		    LimitArea area = limitAreaService.selectByPrimaryKey(areaId);
			limitAreaService.updateDeleteStatus(areaId);
            //将这个fenceId变为可用状态
//			fenceIdService.updateFalseStatus(area.getFence());
            //下发围栏点指令
//            fenceSend(defalutDot,area.getDepts(),area.getTypes());
		}catch(Exception e){
			rd.setCode(-1);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}
		rd.setCode(GloabalConstant.SUCCESS);
		return rd;
	}

    @RequestMapping(value="/fence", method=RequestMethod.POST)
    public String fenceCallback(@RequestBody String data){
        logger.info("callback->"+data);
        JSONObject dataJson = JSON.parseObject(data);
        Map param = new HashMap();
        param.put("devid",dataJson.getString("devid"));
        param.put("status",dataJson.getInteger("status"));
        fenceSendMapper.updateByDevid(param);

        JSONObject result = new JSONObject();
        result.put("code",0);
        result.put("message","success");
        return result.toJSONString();
    }

    public static final String defalutDot = "102.92460432493897,25.090330755395456;102.92460432493897,25.090330755395456;102.92460432493897,25.090330755395456";



    private void fenceSend(String area,String depts,String types){
        //取可用的围栏id，获取相关车辆编号列表，http下发指令
        FenceId fenceId = fenceIdService.selectUsableId();

        Map<String,Object> param = new HashMap<>();
        String[] deptsArr = depts.split(",");
        List<String> deptList = new ArrayList<String>();
        for(String rr : deptsArr) {
            deptList.add(rr);
        }

        String[] typesArr = types.split(",");
        List<String> typeList = new ArrayList<String>();
        for(String rr : typesArr) {
            typeList.add(rr);
        }

        param.put("department", deptList);
        param.put("vehicletype", typeList);
        List<Map> vidList = vehicleService.selectIdByUser(param);

        int npts = area.split(";").length;
        area = area.replaceAll(";",",");
        for(Map item:vidList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("devid",item.get("devid"));
            JSONObject jsonFence = new JSONObject();
            jsonFence.put("id",fenceId.getFid());
            jsonFence.put("npts",npts);
            jsonFence.put("pts",area);
            jsonFence.put("alm",3);
            jsonFence.put("speed",100);
            jsonObject.put("fence",jsonFence);
            //System.out.println(jsonObject.toJSONString());
            int code = httpService.post("http://114.112.63.147:8443/devctl/api/v1.0/fence", HttpContentType.TEXT,jsonObject.toJSONString());
            FenceSend fenceSend = new FenceSend();
            fenceSend.setDevid((String)item.get("devid"));
            fenceSend.setFenceid(fenceId.getFid());
            if (code == 200)
                fenceSend.setStatus(0);
            else
                fenceSend.setStatus(1);

            fenceSendMapper.insert(fenceSend);
        }
    }

    @RequestMapping(value="/limitArea/fence", method=RequestMethod.GET)
    public String fenceTest(){
        //取可用的围栏id，获取相关车辆编号列表，http下发指令
        String area = "102.92460432493897,25.090330755395456;102.92784265404424,25.09105214095868;102.92636139798856,25.095421624236394;102.92460432493897,25.090330755395456";
        FenceId fenceId = fenceIdService.selectUsableId();
        int npts = area.split(";").length;
        area = area.replaceAll(";",",");
        //for(Map item:vidList){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("devid","8a3892e2");
        JSONObject jsonFence = new JSONObject();
        jsonFence.put("id",fenceId.getFid());
        jsonFence.put("npts",npts);
        jsonFence.put("pts",area);
        jsonFence.put("alm",3);
        jsonFence.put("speed",100);
        jsonObject.put("fence",jsonFence);
        System.out.println("send->"+jsonObject.toJSONString());
        int code = httpService.post("http://114.112.63.147:8443/devctl/api/v1.0/fence", HttpContentType.TEXT,jsonObject.toJSONString());
        //}

        return "0";
    }

}
